package com.spzx.order.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.DateUtils;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constants.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.Product;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.domain.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.service.IOrderInfoService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-10-13
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService
{
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;


    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RabbitService rabbitService;


    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id)
    {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    /**
     * 订单详情
     */
    @Override
    public TradeVo orderTradeData() {
        //获取登陆者的id
        Long userId = SecurityContextHolder.getUserId();

        //1.获取选中购物车的信息
        R<List<CartInfo>> cartCheckedList = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if(cartCheckedList.getCode() ==R.FAIL){
            throw  new ServiceException("获取选中购物车信息降级 ："+cartCheckedList.getMsg());
        }
        List<CartInfo> cartInfoList = cartCheckedList.getData();
        if(CollectionUtils.isEmpty(cartInfoList)){
            throw  new ServiceException("用户的购物车为空 无法下单");
        }

        //2.将集合泛型从购物车改为订单明细  选中的商品——> 结算商品列表
        List<OrderItem> orderItemList = new ArrayList<>();
        orderItemList = cartInfoList.stream().map(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            //拷贝
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).collect(Collectors.toList());

        //3.结算总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }


        //4.//渲染订单确认页面-生成用户流水号
        String tradeNo = this.generateTradeNo(userId);

        //5.返回给前端
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setTradeNo(tradeNo);
        tradeVo.setOrderItemList(orderItemList);

        return tradeVo;

    }

    /**
     * 下单--用户提交订单
     * @param orderForm
     * @return
     */
    @Override
    public Long submitOrder(OrderForm orderForm) {
        //获取登陆者的id
        Long userId = SecurityContextHolder.getUserId();
        //1.验证用户是否通过浏览器回退进行重复提交订单


        //1.3 采用Lua脚本保证判断删除流水号原子性 KEYS[1]:流水号Key    ARGV[1]：用户流水号
        /*从缓存中获取数据 和orderForm.tradeNo比较是否一样 如果一样就删除数据*/
        String userTradeKey = "user:tradeNo:" + userId;
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo());
        if (flag == 0) {
            throw new ServiceException("请勿重复提交订单，请尝试重试");
        }

        //2. 判断购物项（判断提交过来的数据是否为空）
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if(CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("请求不合法");
        }

        //3.订单校验
        //3.1.校验价格
        //先获取提交过来的价格id
        List<Long> skuList = orderItemList.stream().map(orderItem -> orderItem.getSkuId()).toList();
        //获取数据库最新价格
        R<List<SkuPrice>> skuPriceList = remoteProductService.getSkuPriceList(skuList, SecurityConstants.INNER);

        if(skuPriceList.getCode() ==R.FAIL){
            throw new ServiceException("批量查询价格出现降级了："+ skuPriceList.getMsg());
        }
        List<SkuPrice> priceListData = skuPriceList.getData();
        //拿到skuId和最新价格组成map
        Map<Long, BigDecimal> skuIdToSkuPriceMap = priceListData.stream().collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        //价格是否存在不一致的情况
        String priceCheckResult ="";
        for (OrderItem orderItem : orderItemList) {
            int flag1 = orderItem.getSkuPrice().compareTo(skuIdToSkuPriceMap.get(orderItem.getSkuId()));
            if(flag1 !=0){
                priceCheckResult += orderItem.getSkuName() + "价格变动了，请重新提交";
            }
        }
        //更新购物车价格 字符串为空 价格都相同
        if(StringUtils.isNotEmpty(priceCheckResult)){
            remoteCartService.updateCartPrice(userId, SecurityConstants.INNER);
                throw  new ServiceException(priceCheckResult);
        }

        //TODO 3.2校验库存并锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            //默认就是 skuLockVo.setIsHaveStock(false);
            return skuLockVo;
        }).collect(Collectors.toList());
        R<String> stringR = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if(stringR.getCode() ==R.FAIL){
            //降级 锁库失败
            throw  new ServiceException(stringR.getData());
        }


        //4.下单--insert orderInfo表添加数据
        Long  orderId =null;
        try {
            //下单成功 添加数据
            orderId = this.saveOrder(orderForm);
            //减少库存
            //rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_MINUS,SecurityConstants.INNER);
        } catch (Exception e) {
            e.printStackTrace();
            //解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }

        //5.删除已选购物车
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);

        //6.发送延迟消息 取消订单
        rabbitService.sendDelayMessage(MqConst.EXCHANGE_CANCEL_ORDER,MqConst.ROUTING_CANCEL_ORDER,String.valueOf(orderId),MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    /**
     *根据拥护id返回结算实体类
     * @param skuId
     * @return
     */
    @Override
    public TradeVo buy(Long skuId) {

        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        //添加结算商品金额数据 //获取商品基本信息
        R<ProductSku> productSku = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
        if(productSku.getCode()==R.FAIL){
            throw  new ServiceException("获取商品基本信息降级："+ productSku.getMsg());
        }
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getData().getSkuName());
        orderItem.setThumbImg(productSku.getData().getThumbImg());
        orderItem.setSkuPrice(productSku.getData().getSalePrice());
        orderItem.setSkuNum(1);
        //添加到集合 返回前端
        orderItemList.add(orderItem);

        //获取交易号   存到缓存中
        String tradeNo = this.generateTradeNo(SecurityContextHolder.getUserId());


        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        //结算总金额 就是商品的价格 单个
        tradeVo.setTotalAmount(orderItem.getSkuPrice());

        return tradeVo;
    }

    /**
     * 返回用户订单信息 根据用户订单状态
     * @param orderStatus 用户订单状态
     * @return
     */
    @Override
    public List<OrderInfo> listByStatus(Integer orderStatus) {
        //登陆者id
        Long userId = SecurityContextHolder.getUserId();
        //根据用户id查询用户订单详情页
        List<OrderItem> orderItemList = orderItemMapper.selectByUserId(userId ,orderStatus);

        //获取商品的基本信息
        List<OrderInfo> orderInfos =new ArrayList<>();

        if(orderStatus==null) {
            orderInfos = orderInfoMapper.selectList(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getUserId, userId));
        }else {
             orderInfos = orderInfoMapper.selectList(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getUserId, userId).eq(OrderInfo::getOrderStatus, orderStatus));

        }

        List<OrderInfo> orderInfoList = orderInfos.stream().map(orderInfo -> {
            orderInfo.setOrderItemList(orderItemList);
            return orderInfo;
        }).toList();

        return orderInfoList;
    }


    @Override
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("用户取消订单");
            orderInfoMapper.updateById(orderInfo);
            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1L);
            orderLog.setNote("用户取消订单");
            orderLogMapper.insert(orderLog);
            //发送MQ消息通知商品系统解锁库存 TODO
        }
    }

    //延迟发送消息后 取消订单
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processCloseOrder(long parseLong) {
        OrderInfo orderInfo = orderInfoMapper.selectById(parseLong);
        if(null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) {
            orderInfo.setOrderStatus(-1);
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1L);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }





    @Transactional(propagation = Propagation.REQUIRED)
    public Long saveOrder(OrderForm orderForm) {
        //往order 添加数据
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(SecurityContextHolder.getUserId());
        orderInfo.setNickName(SecurityContextHolder.getUserName());
        orderInfo.setOrderNo(orderForm.getTradeNo());
        //订单总额和原价金额是一样的 获取总价
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setOriginalTotalAmount(totalAmount);
        BigDecimal bigDecimal = new BigDecimal(0);
        orderInfo.setCouponAmount(bigDecimal);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //收货人姓名
        R<UserAddress> userAddress = remoteUserAddressService.getUserAddress(SecurityContextHolder.getUserId(), SecurityConstants.INNER);
        if(userAddress.getCode()==R.FAIL){
            throw new ServiceException("调用根据用户名查询用户地址信息降级了:"+userAddress.getMsg());
        }
        UserAddress userAddressData = userAddress.getData();
        orderInfo.setReceiverName(userAddressData.getName());
        orderInfo.setReceiverPhone(userAddressData.getPhone());
        orderInfo.setReceiverTagName(userAddressData.getTagName());
        orderInfo.setReceiverProvince(userAddressData.getProvinceCode());
        orderInfo.setReceiverCity(userAddressData.getCityCode());
        orderInfo.setReceiverDistrict(userAddressData.getDistrictCode());
        orderInfo.setReceiverAddress(userAddressData.getFullAddress());
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo);


        //保存订单明细
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        //记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0L);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();


    }


    /**
     * 渲染订单确认页面-生成用户流水号
     *
     * @param userId
     * @return
     */
    private String generateTradeNo(Long userId) {
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }
}
